package com.gitee.feizns.quickstart.dict.spring.boot.autoconfigure;

import com.gitee.feizns.quickstart.dict.ConcurrentHashMapDictDepositor;
import com.gitee.feizns.quickstart.dict.Dict;
import com.gitee.feizns.quickstart.dict.DictDepositor;
import com.gitee.feizns.quickstart.dict.Permission;
import com.gitee.feizns.quickstart.dict.spring.boot.autoconfigure.db.mybatis.flex.MybatisFlexQkDepositor;
import com.gitee.feizns.quickstart.dict.spring.boot.autoconfigure.db.mybatis.flex.pojo.QkDict;
import com.gitee.feizns.quickstart.jackson.Val;
import com.mybatisflex.core.activerecord.Model;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.SchedulingConfigurer;

import javax.persistence.Entity;

/**
 * dict 自动配置
 * @author feizns
 * @since 2024/12/20
 */
@AutoConfiguration
@ConditionalOnClass({Entity.class, Model.class})
@ConditionalOnMissingBean(DictDepositor.class)
@EntityScan("com.gitee.feizns.quickstart.dict.spring.boot.autoconfigure.db.mybatis.flex.pojo")
@MapperScan("com.gitee.feizns.quickstart.dict.spring.boot.autoconfigure.db.mybatis.flex.mapper")
public class MybatisFlexQkDictAutoConfigure {

    /**
     * dict 条目重置 cron
     */
    public static final QkDict DictEntriesResetCron = QkDict.of("dict-entries-reset-cron", "0 0/5 * * * ?", Permission.ReadOnly, "从数据库抓取字典间隔");

    /**
     * Mybatis Flex QK dict 存款器
     * @return {@link DictDepositor }
     */
    @Bean(name = QkDictBeanNames.Depositor)
    @DependsOn({QkDictBeanNames.Mapper})
    public DictDepositor<QkDict> qkDictDepositor() {
        DictDepositor<QkDict> depositor = new ConcurrentHashMapDictDepositor<>(new MybatisFlexQkDepositor<>(QkDict::getKey));
        depositor.reload();
        Dict.Depositor.set(depositor);
        return depositor;
    }

    /**
     * QK dict 调度配置器
     * @return {@link SchedulingConfigurer }
     */
    @Bean
    public SchedulingConfigurer qkDictSchedulingConfigurer(DictDepositor<QkDict> depositor) {
        return taskRegistrar -> {
            taskRegistrar.addCronTask(depositor::reload, Val.of(Dict.getIfAbsentPut(DictEntriesResetCron.getKey(), DictEntriesResetCron).getValue()).stringValue());
        };
    }

}
